<template>
	<view class="tree-node" @click="handleClick">
		<view class="node-content" :class="{ 'node-expanded': node.expanded }">
			<text class="node-icon">{{ node.children?.length ? (node.expanded ? '-' : '+') : '' }}</text>
			{{ node.name }}
		</view>
		<scroll-view v-if="node.expanded && node.children" class="children-container" scroll-y
			@scrolltolower="loadMoreChildren">
			<tree-node v-for="child in node.children" :key="child.id" :node="child" @select="handleSelect" />
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: 'TreeNode',
		props: {
			node: {
				type: Object,
				required: true
			}
		},
		methods: {
			// 节点点击事件
			handleClick(event) {
				event.stopPropagation();
				this.$emit('node-click', this.node);
			},
			// 子节点选择事件
			handleSelect(childNode) {
				this.$emit('select', childNode);
			},
			// 加载更多子节点（模拟分页）
			loadMoreChildren() {
				if (!this.node.loading) {
					this.node.loading = true;
					setTimeout(() => {
						const newChildren = [{
							id: Date.now(),
							name: `子节点${this.node.children.length + 1}`
						}];
						if (!this.node.children) {
							this.$set(this.node, 'children', []);
						}
						this.node.children.push(...newChildren);
						this.node.loading = false;
					}, 1000);
				}
			}
		}
	};
</script>

<style scoped>
	.tree-node {
		padding: 15rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.node-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		cursor: pointer;
		transition: background 0.2s;
	}

	.node-icon {
		margin-right: 10rpx;
		font-size: 24rpx;
	}

	.children-container {
		height: 300rpx;
		margin-top: 10rpx;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.node-expanded .node-icon {
		transform: rotate(90deg);
	}
</style>